<?php
class Directory_invoice_model extends MY_Model {
    function Directory_invoice_model() {
        parent::MY_Model();        
        $this->directory_user_table = "directory_user";
        $this->directory_invoice_table = "directory_invoice";
        $this->directory_company_table = "directory_company";
        $this->directory_subscription_type_table = "directory_subscription_type";
        $this->bank_info_table = "bank_info";
    }
    
    function get_company_invoice($company_id){
        if (!empty($company_id)) {        
	    $subscription = $this->directory_subscription_type_table;
	    $invoice = $this->directory_invoice_table;
	    //$this->db->where('id_user',$company_id);
        $this->db->select("{$invoice}.*,{$subscription}.active_time, {$subscription}.price, {$subscription}.discount_label");	
	    $this->db->join($subscription,"{$invoice}.payment_type = {$subscription}.id",'left')->order_by("{$invoice}.id",'desc');	
            $query = $this->db->get_where($invoice, array('id_user' => $company_id,'status' => 'paid'));
            
        //$query = $this->db->get_where($invoice,array('id_user' => $company_id));
            //die($this->db->last_query());
            if ($query->num_rows() > 0) {
                $result = $query->result_array();
                return $result;
            } else {
                return false;
            }
        }
    }

    function get_invoice($invoice_number){
        if (!empty($invoice_number)) {        
	    $subscription = $this->directory_subscription_type_table;
	    $invoice = $this->directory_invoice_table;
	    $this->db->where('id_invoice',$invoice_number);	
	    $this->db->join($subscription,"{$invoice}.payment_type = {$subscription}.id");	
            $query = $this->db->get($invoice);
	    //echo $this->db->last_query();
            if ($query->num_rows() > 0) {
                $result = $query->row_array();
                return $result;
            } else {
                return false;
            }
        }
    }
    
    function insert_invoice($id_user, $company, $contact, $contact_number, $invoice_for,
    $created_date, $paid_date, $payment_in, $item_price, $item_tax, $total_paid, $status = 'pending', $paid_until, $payment_type) {        
        $hash = uniqid(md5($company . $contact . $contact_number . $invoice_for . $created_date));
        $data = array(
            'id_user' => $id_user, 
            'company' => $company, 
            'contact' => $contact,
            'contact_number' => $contact_number, 
            'invoice_for' => $invoice_for,
            'created_date' => $created_date,
            'paid_date' => $paid_date, 
            'payment_in' => $payment_in, 
            'item_price' => $item_price,
            'item_tax' => $item_tax, 
            'total_paid' => $total_paid, 
            'status' => $status,
            'hash' => $hash, 
            'paid_until'=>$paid_until,
            'payment_type'=>$payment_type,
        );
        
        //echo "<pre>";
        //print_r($data);
        //die();
        //$this->add($data);
        $this->db->insert($this->directory_invoice_table, $data);
        $id_invoice = $this->db->insert_id();//$this->getLastId();
        $invoice_number = str_pad($id_invoice, 5, '0', STR_PAD_LEFT);
        $data2 = array('id_invoice' => 'TD'.$invoice_number);	
        
        //$condition = "id = '{$id_invoice}'";
        //$this->update($data2, $condition);
        /*$array_update = array(
          'image'=>$file_name,
          'caption'=>$caption,
          );*/
        $this->db->where('id',$id_invoice);
        $this->db->update($this->directory_invoice_table, $data2);
        
        $this->db->where('id',$id_user);
        $this->db->update($this->directory_user_table,array('paid_until' => $paid_until));
       
        return $hash;
    }
    
    function delete_invoice($invoice_id){        
        $this->db->delete($this->directory_invoice_table, array('id' => $invoice_id)); 
    }
    function get_bank_info($bank_id =''){
        if (!empty($bank_id)) {        
            $query = $this->db->get_where($this->bank_info_table, array('id' => $bank_id));
            if ($query->num_rows() > 0) {
                $result = $query->row_array();
                return $result;
            } else {
                return false;
            }
        }else{
            $query = $this->db->get($this->bank_info_table);
            if ($query->num_rows() > 0) {
                $result = $query->result_array();
                return $result;
            } else {
                return false;
            }
	}
    }
    function create_invoice_bt($user_id, $subscription_selected,$bank_select){
      $hash = md5($user_id.$subscription_selected.$bank_select.date('U'));
      $this->load->model('Directory_company_model');
      $this->load->model('Directory_user_model');
      $bank_detail = $this->get_bank_info($bank_select);
      $subscription_detail = $this->Directory_company_model->get_subscription_type($subscription_selected);
      $company_detail = $this->Directory_company_model->get_company_detail($user_id);
      $user_detail = $this->Directory_user_model->get_detail($user_id);
      $payment_type = $subscription_type['active_time'];
      $payment_for_text = "Muscle Cars ".$subscription_detail['active_time']." Subscription";
      
     /* $data = array(
	      'id_user'=>$user_id,
	      'company'=>$company_detail['company'],
	      'created_date'=>date('Y-m-d H:i:s'),
	      'payment_in'=>'EFT',
	      'bank_selected'=>$bank_select,
	      'status'=>'pending',
	      'invoice_for'=>$payment_for_text,
	      'total_paid'=>$subscription_detail['price'],
	      'payment_type'=>$subscription_selected,
	      'hash'=>$hash,
	      );*/
     // $this->db->insert($this->directory_invoice_table,$data);
      //$id_invoice = $this->db->insert_id();
      $id_invoice = rand(rand(1,999),999999);
      $invoice_number = "TD".str_pad($id_invoice,6,0,STR_PAD_LEFT);
      /*$data_invoice = array(
	      'id_invoice'=>$invoice_number
	      );*/
      //$this->db->update($this->directory_invoice_table,$data_invoice);
      $this->send_invoice_mail($user_detail['email'], $user_detail['first_name']." ".$user_detail['surename'],$subscription_detail,$bank_detail,$invoice_number);
      $this->send_invoice_mail_admin($company_detail,$subscription_detail,$bank_detail,$invoice_number);
      return $invoice_number;
    }
    
    function create_invoice_free($user_id){//added
        $subscription_selected='0';
        $hash = md5($user_id.$subscription_selected.date('U'));
        $this->load->model('Directory_company_model');
        $this->load->model('Directory_user_model');
        $this->load->helper("date");
        $subscription_detail = $this->Directory_company_model->get_subscription_type($subscription_selected);
        $company_detail = $this->Directory_company_model->get_company_detail($user_id);
        $user_detail = $this->Directory_user_model->get_detail($user_id);
        $payment_for_text = "Turn It Around Free Trial Subscription";
        $data = array(
	      'id_user'=>$user_id,
	      'company'=>$company_detail['company'],
	      'created_date'=>date('Y-m-d H:i:s'),
	      'payment_in'=>'Free Trial',
	      'status'=>'paid',
	      'invoice_for'=>$payment_for_text,
	      'total_paid'=>$subscription_detail['price'],
	      'payment_type'=>$subscription_selected,
          'paid_date'=>date('Y-m-d H:i:s'),
          'paid_until'=>date('Y-m-d H:i:s',mktime(0,0,0,date("m")+3,date("d"),date("Y"))),
	      'hash'=>$hash,
	      );
       $this->db->insert($this->directory_invoice_table,$data);
       $id_invoice = $this->db->insert_id();
      $invoice_number = "TD".str_pad($id_invoice,6,0,STR_PAD_LEFT);
      $data_invoice = array(
	      'id_invoice'=>$invoice_number
	      );
      $this->db->where('id',$id_invoice);
      $this->db->update($this->directory_invoice_table,$data_invoice);
      $return['ref_code'] = $invoice_number;
      $return['description'] = $payment_for_text;
      return $return;
    }
    
    function check_invoice_free($user_id){//added
        $query = $this->db->query("select * from ".$this->directory_invoice_table." where id_user='$user_id' and status='paid'");
        $num_rows = $query->num_rows();
        return $num_rows;
    }
    
    function create_invoice_cc($user_id, $subscription_selected){
      $hash = md5($user_id.$subscription_selected.date('U'));
      $this->load->model('Directory_company_model');
      $this->load->model('Directory_user_model');
      $subscription_detail = $this->Directory_company_model->get_subscription_type($subscription_selected);
      $company_detail = $this->Directory_company_model->get_company_detail($user_id);      
      $user_detail = $this->Directory_user_model->get_detail($user_id);
      $payment_type = $subscription_type['active_time'];
      $payment_for_text = "Muscle Cars ".$subscription_detail['active_time']." Subscription";
      $data = array(
	      'id_user'=>$user_id,
	      'company'=>$company_detail['company'],
	      'created_date'=>date('Y-m-d H:i:s'),
	      'payment_in'=>'cc',
	      'status'=>'pending',
	      'invoice_for'=>$payment_for_text,
	      'total_paid'=>$subscription_detail['price'],
	      'payment_type'=>$subscription_selected,
	      'hash'=>$hash,
	      );
      $this->db->insert($this->directory_invoice_table,$data);
      $id_invoice = $this->db->insert_id();
      $invoice_number = "TD".str_pad($id_invoice,6,0,STR_PAD_LEFT);
      $data_invoice = array(
	      'id_invoice'=>$invoice_number
	      );
      $this->db->where('id',$id_invoice);
      $this->db->update($this->directory_invoice_table,$data_invoice);
      //$this->send_invoice_mail($user_detail['email'], $user_detail['first_name']." ".$user_detail['surename'],$subscription_detail,$bank_detail);
      //$this->send_invoice_mail_admin($company_detail,$subscription_detail,$bank_detail);
      $return['ref_code'] = $invoice_number;
      $return['description'] = $payment_for_text;
      $return['total_paid'] = $subscription_detail['price'];
      return $return;
    }
  function send_invoice_mail($email,$name,$subscription_detail,$bank_detail,$invoice_number){
    $config = array(
      'mailtype'=>'html'
    );
    $data = array(
      'name'=>$name, 
      'email'=>$email, 
      'subscription'=>$subscription_detail, 
      'bank'=>$bank_detail, 
      'ref_code'=>$invoice_number, 
    );
    $email_content = $this->load->view(TEMPLATE_NAME.'/front/mail/directory_payment_bt',$data, true);
    $this->load->library('email');
    $this->email->initialize($config);
    //$this->email->from('noreply@turnitoround.co.za', 'Turn It Around');
    $this->email->from('noreply@musclecars.co.za', NOREPLY_ADD);
    $this->email->to($email);
    //$this->email->cc('another@another-example.com');
    //$this->email->bcc('them@their-example.com');
    $this->email->subject('Muscle Cars - Bank Payment Instruction');
    $this->email->message($email_content);
    if($this->email->send()){
      return TRUE;
    }else{
      return FALSE;
    }

  }
  function send_invoice_mail_admin($company_detail,$subscription_detail,$bank_detail,$invoice_number){
    $config = array(
      'mailtype'=>'html'
    );
    $data = array(
      'subscription'=>$subscription_detail, 
      'bank'=>$bank_detail, 
      'ref_code'=>$invoice_number, 
    );
    $email_content = $this->load->view(TEMPLATE_NAME.'/front/mail/directory_payment_bt_admin',$data, true);
    $this->load->library('email');
    $this->email->initialize($config);
    //$this->email->from('noreply@turnitoround.co.za', 'Turn It Around');
    $this->email->from('noreply@musclecars.co.za', NOREPLY_ADD);
    //$this->email->to('admin@turnitoround.co.za');
    //$this->email->to('ibnu.triyono@gmail.com');
    //$this->email->to('arunuba@gmail.com');
    $this->email->to('gerald@in-detail.com');
    //$this->email->cc('another@another-example.com');
    //$this->email->bcc('them@their-example.com');
    $this->email->subject('Muscle Cars - Check bank transfer payment');
    $this->email->message($email_content);
    if($this->email->send()){
      return TRUE;
    }else{
      return FALSE;
    }

  }

    function set_user_listing($user_id, $listing_active = '0'){
	$this->db->where('id',$user_id);
	$data = array(
		'listing_active'=>$listing_active
	);
	$this->db->update($this->directory_company_table, $data);
    }
  /*
   * method get_last_paid_until
   * @description untuk mengambil tanggal paid_until terakhir , normalnya berada di tabel directory_user
   *
   */
  function get_last_paid_until($user_id){
      $user = $this->directory_user_table;
      $this->db->where('id',$user_id);
      $query = $this->db->get($user);
      if($query->num_rows() > 0){
	$return = $query->row_array();
	if($return['paid_until'] == '0000-00-00 00:00:00'){
	  $paid_until = date('Y-m-d H:i:s');
	}else{
	  $paid_until = $return['paid_until'];
	}
	return $paid_until;
      }else{
	return FALSE;
      }

  }
    function set_invoice_status($invoice_number, $status = 'pending'){
	$invoice_detail = $this->get_invoice($invoice_number);
	//print_r($invoice_detail);
	if($status == 'paid'){
	  $paid_until = $this->get_last_paid_until($invoice_detail['id_user']);
	  //echo $paid_until;
	  //echo date('Y-m-d H:i:s', strtotime($paid_until.' +'.$invoice_detail['active_time'])); 
	  $data = array(
	      'status'=>$status,
	      'paid_date'=>date('Y-m-d H:i:s'),
	      'paid_until'=>date('Y-m-d H:i:s', strtotime($paid_until.' +'.$invoice_detail['active_time'])),
	  );
	  $this->db->where('id',$invoice_detail['id_user']);
	  $this->db->update($this->directory_user_table, array('paid_until'=>date('Y-m-d H:i:s',strtotime($paid_until.' +'.$invoice_detail['active_time']))));
	  //echo $this->db->last_query();
	}else{
	  $data = array(
		'status'=>$status
	  );
	}
	$this->db->where('id_invoice',$invoice_number);
	$this->db->update($this->directory_invoice_table, $data);
	//echo $this->db->last_query();
    }
    function get_payment_list($id_company=''){
	if($id_company != ''){
	    $invoice = $this->directory_invoice_table;
	    $subscription = $this->directory_subscription_type_table;
	    $this->db->where("{$invoice}.id_user",$id_company);
	    $this->db->where("{$invoice}.status",'paid');
	    $this->db->join($subscription, "{$subscription}.id = {$invoice}.payment_type");
	    $query = $this->db->get($invoice);        
	    if($query->num_rows() > 0){
	      $return = $query->result_array();
	      return $return;
	    }else{
	      return FALSE;
	    }
	}else{
	    return FALSE;
	}
    }
        
    
}
?>
